package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2024-04-08  19:13
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true) {
            Socket clientSocket = serverSocket.accept();
/*
            多线程
            Thread thread = new Thread(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
           thread.start();
*/
            //线程池
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

    }

    //处理一次连接，连接过程中会涉及到多次请求响应交互
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream(); OutputStream outputStream  = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            while(true) {
                if(!scanner.hasNext()) {
                    //读取完毕客户端断开连接
                    System.out.printf("[%s:%d] 客户端下线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //1.读取请求并解析 注意隐藏约定，next需要读到空白结束返回：/n “ ”，因此客户端发来的请求必须以空白符结尾
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //把响应返回客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲区
                printWriter.flush();
                System.out.printf("[%s:%d] req: %d, resp: %d\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } finally {
            clientSocket.close();
        }

    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
